package com.chatroom.client.ui;

import com.chatroom.client.Client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ModernLoginFrame extends JFrame {
  private JTextField usernameField;
  private JPasswordField passwordField;
  private JPasswordField confirmField; // 注册专用
  private JCheckBox rememberMeBox;
  private JButton actionButton;
  private JLabel switchLabel;
  private JLabel forgotLabel;
  private boolean isLoginMode = true;

  public ModernLoginFrame() {
    setTitle("登录 - ChatRoom");
    setSize(700, 420);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setLayout(new BorderLayout());
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      UIManager.put("Label.font", new Font("微软雅黑", Font.PLAIN, 16));
      UIManager.put("Button.font", new Font("微软雅黑", Font.PLAIN, 16));
      UIManager.put("TextField.font", new Font("微软雅黑", Font.PLAIN, 16));
      UIManager.put("TextArea.font", new Font("微软雅黑", Font.PLAIN, 16));
    } catch (Exception e) {
      e.printStackTrace();
    }
    add(createFormPanel(), BorderLayout.WEST);
    add(new IllustrationPanel(), BorderLayout.CENTER);
  }

  private JPanel createFormPanel() {
    JPanel panel = new JPanel() {
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
      }
    };
    panel.setPreferredSize(new Dimension(340, 420));
    panel.setLayout(null);
    updateForm(panel);
    return panel;
  }

  private void updateForm(JPanel panel) {
    panel.removeAll();
    JLabel title = new JLabel(isLoginMode ? "登录" : "注册");
    title.setFont(new Font("微软雅黑", Font.BOLD, 28));
    title.setBounds(40, 40, 200, 40);
    panel.add(title);

    JLabel userLabel = new JLabel("用户名");
    userLabel.setFont(new Font("微软雅黑", Font.PLAIN, 15));
    userLabel.setBounds(40, 85, 80, 20);
    panel.add(userLabel);
    usernameField = new JTextField();
    usernameField.setBounds(40, 110, 260, 38);
    usernameField.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(new Color(180, 180, 180), 1, true),
        BorderFactory.createEmptyBorder(0, 10, 0, 10)));
    usernameField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
    usernameField.setToolTipText("用户名");
    panel.add(usernameField);

    JLabel passLabel = new JLabel("密码");
    passLabel.setFont(new Font("微软雅黑", Font.PLAIN, 15));
    passLabel.setBounds(40, 150, 80, 20);
    panel.add(passLabel);
    passwordField = new JPasswordField();
    passwordField.setBounds(40, 175, 260, 38);
    passwordField.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(new Color(180, 180, 180), 1, true),
        BorderFactory.createEmptyBorder(0, 10, 0, 10)));
    passwordField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
    passwordField.setToolTipText("密码");
    panel.add(passwordField);

    if (isLoginMode) {
      rememberMeBox = new JCheckBox("记住我");
      rememberMeBox.setBounds(40, 225, 80, 30);
      rememberMeBox.setOpaque(false);
      rememberMeBox.setFont(new Font("微软雅黑", Font.PLAIN, 14));
      panel.add(rememberMeBox);

      forgotLabel = new JLabel("忘记密码？");
      forgotLabel.setBounds(180, 225, 120, 30);
      forgotLabel.setForeground(new Color(150, 60, 200));
      forgotLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
      forgotLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
      forgotLabel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
          JOptionPane.showMessageDialog(panel, "请联系管理员重置密码。", "找回密码", JOptionPane.INFORMATION_MESSAGE);
        }
      });
      panel.add(forgotLabel);
    } else {
      JLabel confirmLabel = new JLabel("确认密码");
      confirmLabel.setFont(new Font("微软雅黑", Font.PLAIN, 15));
      confirmLabel.setBounds(40, 215, 80, 20);
      panel.add(confirmLabel);
      confirmField = new JPasswordField();
      confirmField.setBounds(40, 240, 260, 38);
      confirmField.setBorder(BorderFactory.createCompoundBorder(
          BorderFactory.createLineBorder(new Color(180, 180, 180), 1, true),
          BorderFactory.createEmptyBorder(0, 10, 0, 10)));
      confirmField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
      confirmField.setToolTipText("确认密码");
      panel.add(confirmField);
    }

    actionButton = new JButton(isLoginMode ? "登录" : "注册") {
      @Override
      protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g.create();
        // 渐变背景
        GradientPaint gp = new GradientPaint(0, 0, new Color(170, 80, 220), 0, getHeight(), new Color(120, 60, 180));
        g2.setPaint(gp);
        g2.fillRoundRect(0, 0, getWidth(), getHeight(), 22, 22);
        // 阴影
        g2.setColor(new Color(120, 60, 180, 60));
        g2.fillRoundRect(4, getHeight() - 10, getWidth() - 8, 8, 16, 16);
        super.paintComponent(g);
        g2.dispose();
      }
    };
    actionButton.setOpaque(false);
    actionButton.setContentAreaFilled(false);
    actionButton.setFocusPainted(false);
    actionButton.setBorderPainted(false);
    actionButton.setForeground(Color.WHITE);
    actionButton.setFont(new Font("微软雅黑", Font.BOLD, 22));
    actionButton.setBounds(40, isLoginMode ? 275 : 305, 260, 44);
    actionButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    actionButton.addActionListener(e -> {
      if (isLoginMode)
        onLogin();
      else
        onRegister();
    });
    panel.add(actionButton);

    if (isLoginMode) {
      JLabel noAccount = new JLabel("还没有账号？");
      noAccount.setBounds(40, 335, 120, 30);
      noAccount.setFont(new Font("微软雅黑", Font.PLAIN, 13));
      panel.add(noAccount);
      switchLabel = new JLabel("去注册");
      switchLabel.setBounds(160, 335, 80, 30);
    } else {
      JLabel haveAccount = new JLabel("已有账号？");
      haveAccount.setBounds(40, 335, 120, 30);
      haveAccount.setFont(new Font("微软雅黑", Font.PLAIN, 13));
      panel.add(haveAccount);
      switchLabel = new JLabel("去登录");
      switchLabel.setBounds(160, 335, 80, 30);
    }
    switchLabel.setForeground(new Color(150, 60, 200));
    switchLabel.setFont(new Font("微软雅黑", Font.BOLD, 13));
    switchLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    switchLabel.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        isLoginMode = !isLoginMode;
        updateForm(panel);
        panel.repaint();
      }
    });
    panel.add(switchLabel);
    panel.repaint();
    panel.revalidate();
  }

  private void onLogin() {
    String username = usernameField.getText().trim();
    String password = new String(passwordField.getPassword());
    if (username.isEmpty() || password.isEmpty()) {
      JOptionPane.showMessageDialog(this, "用户名和密码不能为空！", "登录失败", JOptionPane.ERROR_MESSAGE);
      return;
    }
    if (UserManager.getInstance().validateUser(username, password)) {
      if (rememberMeBox != null && rememberMeBox.isSelected()) {
        JOptionPane.showMessageDialog(this, "已记住用户名: " + username);
      }
      JOptionPane.showMessageDialog(this, "登录成功！");
      dispose();
      new Client(username);
    } else {
      JOptionPane.showMessageDialog(this, "用户名或密码错误！", "登录失败", JOptionPane.ERROR_MESSAGE);
    }
  }

  private void onRegister() {
    String username = usernameField.getText().trim();
    String password = new String(passwordField.getPassword());
    String confirm = new String(confirmField.getPassword());
    if (username.isEmpty() || password.isEmpty()) {
      JOptionPane.showMessageDialog(this, "用户名和密码不能为空！", "注册失败", JOptionPane.ERROR_MESSAGE);
      return;
    }
    if (!password.equals(confirm)) {
      JOptionPane.showMessageDialog(this, "两次输入的密码不一致！", "注册失败", JOptionPane.ERROR_MESSAGE);
      return;
    }
    if (UserManager.getInstance().registerUser(username, password)) {
      JOptionPane.showMessageDialog(this, "注册成功！请登录。");
      isLoginMode = true;
      updateForm((JPanel) getContentPane().getComponent(0));
    } else {
      JOptionPane.showMessageDialog(this, "用户名已存在！", "注册失败", JOptionPane.ERROR_MESSAGE);
    }
  }

  // 右侧插画面板
  static class IllustrationPanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      GradientPaint gp = new GradientPaint(0, 0, new Color(120, 80, 220), getWidth(), getHeight(),
          new Color(180, 120, 255));
      g2.setPaint(gp);
      g2.fillRect(0, 0, getWidth(), getHeight());
      g2.setColor(new Color(255, 255, 255, 180));
      g2.fillOval(getWidth() - 120, 30, 40, 40);
      g2.setColor(new Color(120, 80, 220, 180));
      g2.fillArc(getWidth() - 110, 35, 30, 30, 90, 180);
      g2.setColor(new Color(255, 255, 255, 180));
      g2.fillRoundRect(getWidth() - 200, 60, 60, 20, 20, 20);
      g2.fillRoundRect(getWidth() - 170, 50, 40, 15, 15, 15);
      g2.fillRoundRect(getWidth() - 80, 90, 50, 18, 18, 18);
      int[] xs = { 80, 160, 240, 300 };
      int[] ys = { 320, 260, 340, 300 };
      int[] rs = { 60, 40, 30, 20 };
      Color[] cs = { new Color(255, 220, 240, 200), new Color(220, 180, 255, 200), new Color(255, 180, 220, 180),
          new Color(200, 180, 255, 180) };
      for (int i = 0; i < xs.length; i++) {
        g2.setColor(cs[i]);
        g2.fillOval(xs[i], ys[i], rs[i], rs[i]);
        g2.setColor(new Color(255, 255, 255, 120));
        g2.fillRect(xs[i] + rs[i] / 2 - 3, ys[i] + rs[i], 6, 60);
      }
    }
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> new ModernLoginFrame().setVisible(true));
  }
}